<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>我的医院床位管理</title>
<link rel="shortcut icon" href="favicon.ico">
<link href="${pageContext.request.contextPath }/bootstrapStyle/css/bootstrap.min.css?v=3.3.5" rel="stylesheet">
<link href="${pageContext.request.contextPath }/bootstrapStyle/css/font-awesome.min.css?v=4.4.0" rel="stylesheet">
<link href="${pageContext.request.contextPath }/bootstrapStyle/css/plugins/dataTables/dataTables.bootstrap.css" rel="stylesheet">
<link href="${pageContext.request.contextPath }/bootstrapStyle/css/animate.min.css" rel="stylesheet">
<link href="${pageContext.request.contextPath }/bootstrapStyle/css/style.min.css?v=4.0.0" rel="stylesheet">
<link href="${pageContext.request.contextPath }/bootstrapStyle/css/plugins/treeview/bootstrap-treeview.css" rel="stylesheet">
<link rel="stylesheet" href="${pageContext.request.contextPath }/bootstrap/css/bundled.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/bootstrap/css/jquery-confirm.css"/>
</head>
<body class="gray-bg">
    <div class="row wrapper wrapper-content animated fadeInRight">
    	<div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>医院部门树-详情</h5>
                </div>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>医院科室</h5>
                </div>
                <!-- <div class="ibox-content">
                    <p>该树实现对医院端部门床位的管理，实现树形可视化，逻辑化管理</p>
                </div> -->
                <div class="ibox-content">
                    <div id="Dept_Tree" class="test">
                    	
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-9">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>部门信息一览</h5>
                </div>
                <div class="ibox-content">
                    <p>这里预览的是每个科室的详细信息</p>
                </div>
                <div class="ibox-content">
                	<div id="ShowDetail" class="">
                    	
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-9">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>床位信息一览（<a>点击左侧选择部门，或点击加号查询二级部门</a>）</h5>
                </div>
                <div class="ibox-content">
                	<div class="btn-group hidden-xs" id="exampleTableEventsToolbar" role="group">
                    	<button type="button" class="btn btn-primary" onclick="AddBerth()">
                        	<i class="glyphicon glyphicon-plus" aria-hidden="true">添加床位</i>
                    	</button>
                    	<button type="button" class="btn btn-primary" onclick="MultiDeleteBerth()" id="MultiDeleteBerth">
                        	<i class="glyphicon glyphicon-trash" aria-hidden="true">删除床位</i>
                   		</button>
                 	</div>
                	<div class="wrapper wrapper-content animated fadeInRight">
        				<div class="row">
        					<div id="ShowBerth" class="">
        						<input type="hidden" id="hospdeptID"><!-- 记录当前点击后的部门ID -->
        						<input type="hidden" id="hospdeptName"><!-- 记录当前点击后的部门名 -->
                                <table class="table table-striped table-bordered table-hover dataTables-example" id="berthTable">
		                        	<thead>
			                        	<tr>
			                            	<th><input type="checkbox" id="checkall"/><abbr title="全选为当前页！！！">全选</abbr></th>
			                                <th>部门</th>
			                                <th>床位号</th>
			                                <th>床位说明</th>
			                            </tr>
		                            </thead>
                            		<tbody>
                            				
                            		</tbody>
                        		</table>
        					</div>
                    	</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="${pageContext.request.contextPath }/bootstrapStyle/js/bundled.js"></script>
    <script src="${pageContext.request.contextPath }/bootstrapStyle/js/jquery.min.js?v=2.1.4"></script>
    <script src="${pageContext.request.contextPath }/bootstrapStyle/js/plugins/dataTables/jquery.dataTables.js"></script>
    <script src="${pageContext.request.contextPath }/bootstrapStyle/js/plugins/dataTables/dataTables.bootstrap.js"></script>
    <script src="${pageContext.request.contextPath }/bootstrapStyle/js/content.min.js?v=1.0.0"></script>
    <script src="${pageContext.request.contextPath }/bootstrapStyle/js/jquery-confirm.js"></script>
    <script src="${pageContext.request.contextPath }/bootstrapStyle/js/plugins/treeview/bootstrap-treeview.js"></script>
    <script type="text/javascript">
    $(function () {
    	InitTree();
    });
    function InitTree(){
		// Some logic to retrieve, or generate tree structure
		var nodes=[];//父节点
		var tnodes=[];//总的节点
		//var str="[";
		$.ajax({
			type:"post",
			url:"${pageContext.request.contextPath}/Main/Berth/myhospDeptInit.action",
			async: true,
			success:function(datamap){
				if(datamap.code=="100"){
					var data=datamap.list;
					for(var i = 0;i < data.length;i++){
						if(data[i].hospdeptfatherid!=0){
							var rows = data[i];
							var tagsNumber = rows.total;
							if(tagsNumber=='null' || tagsNumber==''){
								tagsNumber=Number(0);
							}else{
								tagsNumber=Number(rows.total);
							}
	    					tnodes.push({
	    						id:rows.hospdeptid,
	    						nodeid:rows.hospdeptfatherid,
	    						text:rows.hospdeptname,
	    						tages:tagsNumber,//加载子节点的个数，在每个li标签的后面显示数字
	    					});
	    				}
	    			}
	    			for(var i = 0;i < data.length;i++){
	    				var tnodeskey=[];//分段子节点
	    				//构造父节点
	    				if(data[i].hospdeptfatherid==0){
	    					var row = data[i];
	    					var count1=row.total;
	    					var tagsCount1 = row.total;
	    					var count=0;var tagsCount=0;
	    					if(tagsCount1=='null' || tagsCount1==''){
	    						tagsCount=0;
	    					}else{
	    						tagsCount=Number(tagsCount1);
	    					}
	    					if(count1=='null' || count1==''){
	    						count=0;
	    					}else{
	    						count=Number(count1);
	    					}
	    					for(var j=0;j<tnodes.length;j++){
	    						if(tnodes[j].nodeid==row.hospdeptid){
	    							tnodeskey.push({
	    		    					id:tnodes[j].id,
	    		    					text:tnodes[j].text,
	    		    					tags:[tnodes[j].tages]
	    		    				});
	    							count=Number(count)+Number(tnodes[j].tages);
	    						}
	    					}
	    					nodes.push({//分段加载父节点和子节点
		    					id:row.hospdeptid,
		    					text:row.hospdeptname,
		    					tags:[tagsCount+"/"+count],//加载子节点的个数，在每个li标签的后面显示数字
		    					nodes:tnodeskey
		    				});
	    				}
	    			}
	    			function getTree(){
	    				var StrNode=nodes;
	    	            return StrNode;
	    	        }
	    			$('#Dept_Tree').treeview({
	    		        data: getTree(),         // data is not optional
	    		        color:"#428bca",
	    		        levels: 1,
	    		        multiSelect: true,
	    		        showTags:!0,
	    		        nodeIcon: 'glyphicon glyphicon-user',
	    		        emptyIcon: '', //没有子节点的节点图标
	    		        onNodeChecked: function (event,data) {
	    		        	//alert("onNodeChecked:"+data.id);
	    		        },
	    		        onNodeSelected: function (event, dataSource) {//选中节点事件
	    		        	//$.alert('ID：'+dataSource.id);
	    		        	$("#hospdeptID").val(dataSource.id);//给定hidden值，即该部门的ID
	    		        	$("#hospdeptName").val(dataSource.text.replace(/\(.*?\)/g,''));//给定hidden该节点的name，方便管理者管理
	    		        	//$("#OldhospdeptName").val(dataSource.text.replace(/\(.*?\)/g,''));//去除字符串中的括号及其括号中的内容
	    		        	//alert(dataSource.id);
	    		        	LoadTable(dataSource.id);
	    		        }
	    		    }).treeview('collapseAll', { silent: true });
				}else{
					$.alert(datamap.msg);
				}
    		},error:function(request){
    			$.alert("连接失败！");
    		}
    	});
	}
    function LoadTable(hospberthdeptid){
    	$.ajax({
    		type:"post",
    		url:"${pageContext.request.contextPath}/Main/Berth/gethospitalberth.action",
    		async: true,
    		data:"hospberthdeptid="+hospberthdeptid,
    		success:function(datamap){//查询成功返回数据显示
    			var data1 = datamap.list;
    			$('#ShowDetail')[0].innerHTML="";
    			//$('#berthTable tbody').empty();//上面这两个不可丢失，实现对换标签点击的时候清楚预览版的内容，防止append的内容合到一起
    			$('#berthTable').dataTable().fnClearTable();//清空table表的所有数据，重新加载
    			$('#ShowDetail').append("该部门是："+data1[0].hospdeptname+"<br/>");
    			$('#ShowDetail').append("部门详情信息："+data1[0].hospdeptabs);
    			if(datamap.code=="100"){
    				for(var i=0;i<data1.length;i++){
        				/* $('#berthTable').append("<tr class='gradeX'>"+
                    			"<td><input type='checkbox' name='check' value='"+data[i].hospberthid+"'/></td>"+
                    			"<td>"+data[i].hospdeptname+"</td>"+
                                "<td>"+data[i].hospberthname+"</td>"+
                                "<td>"+data[i].hospberthabs+"</td>"+
                                "<td><a class='J_menuItem' href='#' onclick='DeleteBerth("+data[i].hospberthid+",this)'>删除</a></td>"+
                			"</tr>"); */
                		
                			$("#berthTable").dataTable().fnAddData([
	        					"<input type='checkbox' name='check' value='"+data1[i].hospberthid+"'/>",
	        					data1[i].hospdeptname,
	        					data1[i].hospberthname,
	        					data1[i].hospberthabs
		                		//"<a class='J_menuItem' href='#' onclick='DeleteBerth("+data1[i].hospberthid+",this)'><i class='glyphicon glyphicon-remove' aria-hidden='true'>删除</i></a>"
		                	])
                		
        			}
    			}else{
    				$.alert(data.msg);
    			}
    		},
    		error: function(request) {//查询失败，显示数据查询错误！
    			$('#ShowDetail')[0].innerHTML="";
    			$('#berthTable tbody').empty();
    			$('#ShowDetail').append(" <a style="+'"color:red"'+"><abbr title="+'"数据延迟"'+">数据查询延迟，重试！！！</abbr></a>");
    			$('#berthTable').append(" <a style="+'"color:red"'+"><abbr title="+'"数据延迟"'+">数据查询延迟，重试！！！</abbr></a>");
            }
    	})
    }
	$(document).ready(function(){
    	$(".dataTables-example").dataTable();
	 	//这里是初始化table
		$('#checkall').click(function(){
			$('input[name="check"]').prop("checked",this.checked); 
		});
	});
	function AddBerth(){
		var hospdeptName = $("#hospdeptName").val();
		if(!hospdeptName){
			$.alert({
    		    title: '提示!',
    		    content: "请先选择一个部门",
    		    type: 'red',
    		    typeAnimated: true,
    		    buttons:{确定:function(){}}
    		});
			return false;
		}
		$.confirm({
		    title: hospdeptName+'新增床位',
		    boxWidth: '500px',
		    useBootstrap: false,
		    content: '' +
		    '<form action="" role="form">' +
		    '<div class="form-group">' +
		    '<label>新增床位数</label>' +
		    '<input type="number" placeholder="填写数字，0-10之间" min="1" max="10" class="berthnumber form-control" style="width:200px;" required="true" />' +
		    '</div>' +
		    '<div class="form-group">' +
		    '<label>床位号</label>' +
		    '<input type="text" placeholder="床位号" class="berthname form-control" style="width:200px;" required />' +
		    '</div>' +
		    '<div class="form-group">' +
		    '<label>床位详情</label>' +
		    '<input type="text" placeholder="详情（可不填）" class="berthAbs form-control" style="width:400px;" required />' +
		    '</div>' +
		    '</form>',
		    buttons: {
		        formSubmit: {
		            text: '提交',
		            btnClass: 'btn-blue',
		            action: function () {
		            	var hospdeptID = $("#hospdeptID").val();
		                var berthnumber = this.$content.find('.berthnumber').val();
		                var berthname = this.$content.find('.berthname').val();
		                var berthAbs = this.$content.find('.berthAbs').val();
		                if(!berthname || !berthnumber){
		                    $.alert('填写信息不可为空');
		                    return false;
		                }
		                if(berthnumber<=0 || berthnumber>10){
		                	$.alert('床位数大小区间在1-10');
		                	return false;
		                }
		                if(!(/(^[1-9]\d*$)/.test(berthnumber))){
		                	$.alert('床位数输入不是正整数！');
		                	return false;
		                }
		                var param="hospberthdeptid="+hospdeptID+"&hospberthname="+berthname+"&hospberthabs="+berthAbs;
		                $.confirm({
		        		    title: '提示!',
		        		    content: '是否提交？',
		        		    type: 'blue',
		        		    typeAnimated: true,
		        		    buttons: {
		        		    	确定: function () {
		        		    		for(var i=0;i<berthnumber;i++){
		    		                	//alert(berthname+':'+berthnumber+':'+berthAbs+':'+hospID+':'+hospdeptID);
		    		                	$.ajax({
		    	    		        		type:"post",
		    	    		        		url:"${pageContext.request.contextPath}/Main/Berth/addberthSubmit.action",
		    	    		        		async: true,
		    	    		        		//data:'{"hospberthdeptid":"'+hospdeptID+'","hospberthname":"'+berthname+'","hospberthabs":"'+berthAbs+'","hospid":"'+hospID+'"}',
		    	    		        		data:param,
		    	    		        		success:function(data){
		    	    		        			//$.alert("输出data"+data);
		    	    		        			/* $('#berthTable').append("<tr class='gradeX'>"+
		                                    			"<td><input type='checkbox' name='check' value='"+data+"'/></td>"+
		                                    			"<td>"+hospdeptName+"</td>"+
		        	                                    "<td>"+berthname+"</td>"+
		        	                                    "<td>"+berthAbs+"</td>"+
		        	                                    "<td><a class='J_menuItem' href='#' onclick='DeleteBerth("+data+",this)'>删除</a></td>"+
		                                			"</tr>"); */
		                                		if(data.code=='100'){
		                                			$("#berthTable").dataTable().fnAddData([
		            		        					"<input type='checkbox' name='check' value='"+data.hospberthid+"'/>",
		            		        					hospdeptName,
		            		        					berthname,
		            		        					berthAbs
		        	    		                		//"<a class='J_menuItem' href='#' onclick='DeleteBerth("+data.hospberthid+",this)'><i class='glyphicon glyphicon-remove' aria-hidden='true'>删除</i></a>"
		        	    		                	])
		        	    		        			InitTree();
		                                		}else{
		                                			$.alert(data.msg);
		                                		}
		    	    		        		},
		    	    		        		error:function(request){
		    	    		        			$.alert("连接异常");
		    	    		        		}
		    		                	});
		    		                }
		        		    	},
		        				取消: function () {},
		        		    }	
		        		});
		            }
		        },
		        	关闭: function () {
		        },
		    },
		});
	}
	function DeleteBerth(hospberthid,nowTr){
		$.confirm({
		    title: '提示!',
		    content: '你确定要删除该床位？',
		    type: 'blue',
		    typeAnimated: true,
		    buttons: {
		    	确定: function () {
		    		//$.alert('获取的ID：'+hospberthid);
		    		
		    		$.ajax({
		        		type:"post",
		        		url:"${pageContext.request.contextPath}/Main/Berth/deleteberthSubmit.action",
		        		//contentType:"application/json;charset=utf-8",
		        		async: true,
		        		data:"hospberthid="+hospberthid,
		        		success:function(data){
		        			if(data.code=="100"){
		        				$(nowTr).parent().parent().remove();//清除当前行，动态实现
		        				//$("#berthTable").dataTable().fnDeleteIndex(hospberthid,nowTr);
		        				InitTree();
		        			}else{
		        				$.alert(data.msg);
		        			}
		        		},
		        		error:function(request){
		        			$.alert('数据请求错误！');
		        		}
		    		});
		    	},
				取消: function () {},
		    }	
		});
	}
	function MultiDeleteBerth(){
		var hospberthdeptid= $("#hospdeptID").val();
		//alert(hospberthdeptid);
		var check = document.getElementsByName("check");
    	var check_Str=[];
    	for (i in check){
    		if(check[i].checked){
    			check_Str.push(check[i].value);
    		}
    	}
    	//alert(check_Str);
    	if(check_Str!=""){
    		$.confirm({
    		    title: '提示!',
    		    content: '你确定要一键删除？',
    		    type: 'blue',
    		    typeAnimated: true,
    		    buttons: {
    		    	确定: function () {
    		    		$("#MultiDeleteBerth").html('<i class="fa fa-spinner fa-spin"></i>删除中...');
    		    		$("#MultiDeleteBerth").prop('disabled',true);
    		    		 $.ajax({
    		        		type:"post",
    		        		url:"${pageContext.request.contextPath}/Main/Berth/MultideleteberthSubmit.action",
    		        		//contentType:"application/json;charset=utf-8",
    		        		async: true,
    		        		data:"hospberthids="+check_Str,
    		        		success:function(data){
    		        			$("#MultiDeleteBerth").html('<i class="glyphicon glyphicon-trash" aria-hidden="true">删除床位</i>');
    	    		    		$("#MultiDeleteBerth").prop('disabled',false);
    		        			if(data.code=="100"){
    		        				$.alert('删除成功！');
    		    		    		/* $("input[name='check']:checked").each(function() { // 遍历选中的checkbox
    		    		                n = $(this).parents("tr").index()+1;  // 获取checkbox所在行的顺序
    		    		                $("table#berthTable").find("tr:eq("+n+")").remove();//删除该CheckBox对应的行，实现动态删除
    		    		            }); */
    		    		            LoadTable(hospberthdeptid);
    		    		    		InitTree();
    		        			}else{
    		        				$.alert({
    		        	    		    title: '提示!',
    		        	    		    content: "删除失败！失败床位的ID是:"+data.hospberthid,
    		        	    		    type: 'red',
    		        	    		    typeAnimated: true,
    		        	    		    buttons:{确定:function(){}}
    		        	    		});
    		        			}
    		        		},
    		        		error:function(request){
    		        			$.alert('数据请求错误！');
    		        			$("#MultiDeleteBerth").html('<i class="glyphicon glyphicon-trash" aria-hidden="true">删除床位</i>');
    	    		    		$("#MultiDeleteBerth").prop('disabled',false);
    		        		}
    		    		});
    		        },
    		       	 取消: function () {},
    		    }
    		});
    	}else{
    		$.alert({
    		    title: '提示!',
    		    content: "请先选择一行或多行",
    		    type: 'red',
    		    typeAnimated: true,
    		    buttons:{确定:function(){}}
    		});
    	}
	}
	</script>
</body>
</html>